package org.lotic.xdb.manager;

import java.beans.XMLDecoder;
import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.lotic.ldk.string.StringUtil;
import org.lotic.xdb.session.XDBSingleSession;
import org.lotic.xdb.xml.XMLHandle;

/**
 * XML存储 管理器.
 * 
 * @author lotic
 * 
 */
public class XDBManager {
	/**
	 * 字符串操作.
	 */
	private StringBuffer sb = new StringBuffer(100);
	/**
	 * XDB配置对象.
	 */
	private static XDBConfig config;
	/**
	 * 日志对象.
	 */
	private static final Log log = LogFactory.getLog(XDBManager.class);

	public XDBManager() {
		XDBManager.init();
	}
	
	public XDBManager(XDBConfig conifg) {
		XDBManager.config = config;
		XDBSingleSession.AUTO_COMMIT = config.isAutoCommit();
	}


	/**
	 * 初始化方法.
	 */
	public static void init() {
		XMLHandle handle = new XMLHandle(XDBManager.class.getClassLoader()
				.getSystemResourceAsStream(XDBConfig.CONFIG_FILE_NAME));
		String dataDir = handle.getDocument()
				.selectSingleNode("//xdbConfig/dataDir").getStringValue();
		XDBManager.config = new XDBConfig();
		if (StringUtil.isEmptyOrNull(dataDir)) {
			dataDir = System.getProperty("user.dir");
		}
		XDBManager.config.setDataDir(dataDir);
		String autoCommit = handle.getDocument()
				.selectSingleNode("//xdbConfig/autoCommit").getStringValue();
		if(StringUtil.isNotEmptyOrNull(autoCommit)) {
			boolean ac = Boolean.valueOf(autoCommit);
			XDBManager.config.setAutoCommit(ac);
			XDBSingleSession.AUTO_COMMIT = ac;
		}
		
	}

	public static XDBConfig getXDBConifg() {
		return config;
	}

	/**
	 * 创建XDBSession.
	 * 
	 * @param xdbName
	 *            xdb名称.
	 * @return
	 * @throws Exception
	 */
	public XDBSingleSession createXDBSingleSession(final String xdbName)
			throws Exception {
		sb.delete(0, sb.length());
		String path = sb.append(config.getDataDir()).append(File.separator)
				.append(xdbName).append(XDBConst.XDB_XMLFILE_SUFFIX).toString();
		
		File file = new File(path);
		XDBSingleSession session = XDBSingleSession.getInstance();
		if (file.exists()) {
			session.setFile(file);
			session.setDoc(new XMLHandle(file).getDocument());
		} else {
			session.setFile(file);
			session.setDoc(DocumentHelper
					.parseText(XDBConst.XDB_STRUCT_XML_ROOT));
			session.getDoc().getRootElement().addAttribute("name", xdbName);
		}
		if (log.isInfoEnabled()) {
			log.info("XDBSingleSession 初始化成功 :" + file.getAbsolutePath());
		}
		return session;
	}


}
